<template>
  <div class="app-container">
    <div class="header">
      <div class="header-left">
        <img src="/public/logo.png" alt="" srcset="" style="width: 65px; height: 65px;">
        <h1 style="font-size: 24px; font-weight: bold;">闪图</h1>
      </div>
      <div class="storage-info">
        <el-icon :size="16">
          <Box />
        </el-icon>
        <span>存储使用</span>
        <div class="storage-bar">
          <div class="storage-progress" :class="{
            'warning': storageUsage >= 70 && storageUsage < 90,
            'danger': storageUsage >= 90
          }" :style="{ width: storageUsage + '%' }">
          </div>
        </div>
        <span class="storage-text">{{ storageUsage }}%</span>
      </div>
    </div>

    <div class="nav-tabs">
      <div class="tab-list">
        <div v-for="tab in tabs" :key="tab.name" :class="['tab-item', { active: activeTab === tab.name }]"
          @click="activeTab = tab.name">
          {{ tab.label }}
        </div>
      </div>
    </div>

    <div class="main-content">
      <!-- 图库内容 -->
      <template v-if="activeTab === 'gallery'">
        <div class="tag-filter">
          <div class="tag-item" :class="{ active: currentTag === '全部' }" @click="currentTag = '全部'">
            全部
          </div>
          <div v-for="tag in tags" :key="tag.id" :class="['tag-item', { active: currentTag === tag.name }]"
            @click="currentTag = tag.name">
            {{ tag.name }}
            <span class="tag-count">({{ tag.count || 0 }})</span>
          </div>
          <div class="tag-item add-tag" @click="showTagManageDialog = true">
            管理标签 +
          </div>
        </div>

        <emoji-grid :emojis="filteredEmojis" @deleted="handleEmojiDeleted" />
      </template>

      <!-- 收藏表情内容 -->
      <template v-if="activeTab === 'favorites'">
        <emoji-grid :emojis="favoriteEmojis" />
      </template>

      <!-- 管理内容 -->
      <template v-if="activeTab === 'manage'">
        <div class="manage-section">
          <h2>
            <el-icon>
              <Setting />
            </el-icon>
            存储清理
          </h2>
          <p class="section-desc">优化存储空间，移除不常用的表情包</p>

          <div class="manage-items">
            <div class="manage-item">
              <div class="item-info">
                <h3>压缩大尺寸图片</h3>
                <p>将大于200KB的图片转换为WebP格式</p>
              </div>
              <el-button type="warning" plain :loading="compressing" @click="handleCompress">
                优化 ({{ largeImages.length }}个)
              </el-button>
            </div>

            <div class="manage-item">
              <div class="item-info">
                <h3>清除未使用的表情</h3>
                <p>删除30天内未使用的表情包</p>
              </div>
              <el-button type="warning" plain :loading="cleaning" @click="handleCleanUnused">
                清除 ({{ unusedImages.length }}个)
              </el-button>
            </div>

            <div class="manage-item">
              <div class="item-info">
                <h3>重复图片清理</h3>
                <p>移除重复的表情包</p>
              </div>
              <el-button type="warning" plain :loading="scanning" @click="handleScanDuplicates">
                扫描 ({{ duplicateImages.length }}个)
              </el-button>
            </div>
          </div>

          <h2 class="mt-32">
            <el-icon>
              <Setting />
            </el-icon>
            插件设置
          </h2>

          <div class="settings-items">
            <div class="settings-item">
              <div class="item-info">
                <h3>自动压缩新图片</h3>
                <p>自动优化大于100KB的新图片</p>
              </div>
              <el-switch v-model="settings.autoCompress" @change="handleSettingChange" />
            </div>

            <div class="settings-item">
              <div class="item-info">
                <h3>存储限制</h3>
                <p>当存储超过90%时提醒清理</p>
              </div>
              <el-switch v-model="settings.storageLimit" @change="handleSettingChange" />
            </div>
          </div>

          <div class="action-buttons">
            <el-button type="success" @click="handleExport">导出表情包</el-button>
            <el-upload class="upload-inline" action="#" :auto-upload="false" :show-file-list="false" accept=".json"
              @change="handleImport">
              <el-button type="primary">导入表情包</el-button>
            </el-upload>
          </div>
        </div>
      </template>
    </div>

    <!-- 保存选项对话框 -->
    <save-options-dialog v-model="showSaveDialog" :image-data="currentImage" @save="handleSave" />

    <!-- 标签管理对话框 -->
    <tag-manage-dialog v-model="showTagManageDialog" @tag-updated="loadTags" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useEmojiStore } from './stores/emoji'
import EmojiGrid from './components/EmojiGrid.vue'
import SaveOptionsDialog from './components/SaveOptionsDialog.vue'
import TagManageDialog from './components/TagManageDialog.vue'
import { Picture, Upload, Setting, Box } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'

const emojiStore = useEmojiStore()
const activeTab = ref('gallery')
const currentTag = ref('全部')
const showSaveDialog = ref(false)
const currentImage = ref(null)
const showTagManageDialog = ref(false)
const tags = ref([])

// 使用 store 中的存储使用数据
const storageUsage = computed(() => emojiStore.storageUsage)

// 监听存储使用变化
watch(storageUsage, (newUsage) => {
  // 如果开启了存储限制提醒，且使用率超过90%
  if (settings.value.storageLimit && newUsage > 90) {
    ElMessage.warning('存储空间即将用完，请及时清理')
  }
})

const settings = ref({
  autoCompress: true,
  storageLimit: true
})

const tabs = [
  { name: 'gallery', label: '图库' },
  { name: 'favorites', label: '收藏表情' },
  { name: 'manage', label: '管理' }
]

//初始化
const init = async () => {
  try {
    await emojiStore.init()
    // 确保数据库初始化完成后再添加事件监听器和加载标签
    if (emojiStore.initialized) {
      document.addEventListener('paste', handlePaste)
      console.log('粘贴事件监听器已添加')
      await loadTags()
    } else {
      throw new Error('数据库初始化失败')
    }
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('初始化失败：' + error.message)
  }
}

//加载配置
const loadSettings = () => {
  try {
    const savedSettings = localStorage.getItem('settings')
    if (savedSettings) {
      settings.value = JSON.parse(savedSettings)
    }
  } catch (error) {
    console.error('加载设置失败:', error)
  }
}

// 处理粘贴事件
const handlePaste = async (e) => {
  if (activeTab.value !== 'gallery') return

  try {
    const items = e.clipboardData.items
    let hasImage = false
    console.log('检测到粘贴事件，剪贴板项目：', items)

    for (const item of items) {
      console.log('处理剪贴板项目：', item.type)
      if (item.type.startsWith('image/')) {
        hasImage = true
        const file = item.getAsFile()
        if (file) {
          console.log('获取到图片文件：', file.name, file.size, file.type)
          currentImage.value = {
            data: file,
            name: file.name || new Date().getTime() + '.png',
            size: file.size,
            type: file.type
          }
          showSaveDialog.value = true
          break
        }
      }
    }

    // 检查是否有图片URL
    if (!hasImage) {
      const text = e.clipboardData.getData('text')
      console.log('检查剪贴板文本是否为图片URL：', text)
      if (text && isImageUrl(text)) {
        console.log('检测到图片URL，开始获取图片')
        const response = await fetch(text)
        const blob = await response.blob()
        console.log('成功获取图片blob：', blob.size, blob.type)
        currentImage.value = {
          data: blob,
          name: text.split('/').pop() || '图片.png',
          size: blob.size,
          type: blob.type
        }
        showSaveDialog.value = true
      }
    }
  } catch (error) {
    console.error('处理粘贴事件失败：', error)
    ElMessage.error('处理粘贴内容失败：' + error.message)
  }
}

// 检查是否是图片URL
const isImageUrl = (url) => {
  try {
    const parsed = new URL(url)
    const ext = parsed.pathname.toLowerCase().split('.').pop()
    return ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'].includes(ext)
  } catch {
    return false
  }
}

// 加载标签列表
const loadTags = async () => {
  try {
    console.log('重新加载标签列表')
    tags.value = await emojiStore.getAllTags()
  } catch (error) {
    console.error('加载标签失败:', error)
    ElMessage.error('加载标签失败')
  }
}



const allEmojis = computed(() => {
  return emojiStore.allEmojis
})

const favoriteEmojis = computed(() => emojiStore.favoriteEmojis)

const filteredEmojis = computed(() => {
  if (currentTag.value === '全部') return allEmojis.value
  return allEmojis.value.filter(emoji => emoji.tags && emoji.tags.includes(currentTag.value))
})



const handleSave = async (formData) => {
  try {
    // 保存表情
    await emojiStore.saveEmoji({
      ...currentImage.value,
      name: formData.name,
      tags: formData.tag ? [formData.tag] : []  // 如果有选择标签，将其转换为数组
    })

    showSaveDialog.value = false
    currentImage.value = null
    ElMessage.success('保存成功')

    // 重新加载标签列表以更新计数
    await loadTags()

    // 如果保存到特定标签，切换到该标签
    if (formData.tag) {
      currentTag.value = formData.tag
    }

    // 重新加载表情列表
    await emojiStore.loadEmojis()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败：' + error.message)
  }
}

// 处理表情删除
const handleEmojiDeleted = async () => {
  // 重新加载表情列表
  await emojiStore.loadEmojis()
  // 重新加载标签列表以更新计数
  await loadTags()
}

// 管理页面相关状态
const compressing = ref(false)
const cleaning = ref(false)
const scanning = ref(false)
const largeImages = ref([])
const unusedImages = ref([])
const duplicateImages = ref([])

// 压缩大尺寸图片
const handleCompress = async () => {
  if (compressing.value) return
  try {
    compressing.value = true
    // 获取大于200KB的图片
    largeImages.value = allEmojis.value.filter(emoji => emoji.size > 200 * 1024)
    if (largeImages.value.length === 0) {
      ElMessage.info('没有需要压缩的图片')
      return
    }

    await ElMessageBox.confirm(
      `发现 ${largeImages.value.length} 个大于200KB的图片，是否压缩？`,
      '压缩确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    for (const emoji of largeImages.value) {
      const response = await fetch(emoji.data)
      const blob = await response.blob()
      const compressedFile = await new Promise((resolve, reject) => {
        new Compressor(blob, {
          quality: 0.8,
          maxWidth: 1024,
          maxHeight: 1024,
          convertSize: 200 * 1024,
          success: resolve,
          error: reject
        })
      })

      const base64 = await blobToBase64(compressedFile)
      await emojiStore.updateEmoji(emoji.id, {
        data: base64,
        size: compressedFile.size
      })
    }

    ElMessage.success('压缩完成')
    await emojiStore.loadEmojis()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('压缩失败:', error)
      ElMessage.error('压缩失败：' + error.message)
    }
  } finally {
    compressing.value = false
    largeImages.value = []
  }
}

// 清除未使用的表情
const handleCleanUnused = async () => {
  if (cleaning.value) return
  try {
    cleaning.value = true
    // 获取30天内未使用的表情
    const thirtyDaysAgo = new Date()
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
    unusedImages.value = allEmojis.value.filter(emoji =>
      new Date(emoji.lastUsed || emoji.createdAt) < thirtyDaysAgo
    )

    if (unusedImages.value.length === 0) {
      ElMessage.info('没有需要清理的表情')
      return
    }

    await ElMessageBox.confirm(
      `发现 ${unusedImages.value.length} 个30天内未使用的表情，是否清除？`,
      '清除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    for (const emoji of unusedImages.value) {
      await emojiStore.deleteEmoji(emoji.id)
    }

    ElMessage.success('清除完成')
    await emojiStore.loadEmojis()
    await loadTags()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清除失败:', error)
      ElMessage.error('清除失败：' + error.message)
    }
  } finally {
    cleaning.value = false
    unusedImages.value = []
  }
}

// 扫描重复图片
const handleScanDuplicates = async () => {
  if (scanning.value) return
  try {
    scanning.value = true
    // 通过文件大小和内容hash查找重复
    const hashMap = new Map()
    for (const emoji of allEmojis.value) {
      const response = await fetch(emoji.data)
      const buffer = await response.arrayBuffer()
      const hash = await crypto.subtle.digest('SHA-256', buffer)
      const hashHex = Array.from(new Uint8Array(hash))
        .map(b => b.toString(16).padStart(2, '0'))
        .join('')

      if (hashMap.has(hashHex)) {
        duplicateImages.value.push(emoji)
      } else {
        hashMap.set(hashHex, emoji)
      }
    }

    if (duplicateImages.value.length === 0) {
      ElMessage.info('没有发现重复的表情')
      return
    }

    await ElMessageBox.confirm(
      `发现 ${duplicateImages.value.length} 个重复的表情，是否清除？`,
      '清除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    for (const emoji of duplicateImages.value) {
      await emojiStore.deleteEmoji(emoji.id)
    }

    ElMessage.success('清除完成')
    await emojiStore.loadEmojis()
    await loadTags()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('扫描失败:', error)
      ElMessage.error('扫描失败：' + error.message)
    }
  } finally {
    scanning.value = false
    duplicateImages.value = []
  }
}

// 保存设置
const handleSettingChange = async () => {
  try {
    localStorage.setItem('settings', JSON.stringify(settings.value))
    ElMessage.success('设置已保存')
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error('保存设置失败')
  }
}

// 导出表情包
const handleExport = async () => {
  try {
    const data = {
      emojis: allEmojis.value,
      tags: tags.value,
      exportDate: new Date().toISOString()
    }
    const blob = new Blob([JSON.stringify(data)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `表情包备份_${new Date().toLocaleDateString()}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + error.message)
  }
}

// 导入表情包
const handleImport = async (file) => {
  try {
    const content = await file.raw.text()
    const data = JSON.parse(content)

    await ElMessageBox.confirm(
      `将导入 ${data.emojis.length} 个表情和 ${data.tags.length} 个标签，是否继续？`,
      '导入确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 导入标签
    for (const tag of data.tags) {
      try {
        await emojiStore.addTag(tag.name)
      } catch (error) {
        // 忽略已存在的标签错误
        if (!error.message.includes('已存在')) {
          throw error
        }
      }
    }

    // 导入表情
    for (const emoji of data.emojis) {
      await emojiStore.saveEmoji({
        ...emoji,
        id: undefined  // 让数据库自动生成新ID
      })
    }

    ElMessage.success('导入成功')
    await emojiStore.loadEmojis()
    await loadTags()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('导入失败:', error)
      ElMessage.error('导入失败：' + error.message)
    }
  }
}

// 初始化设置
onMounted(() => {
  const loadingInstance = ElLoading.service()
  init()
  loadSettings()
  loadingInstance.close()
})

onUnmounted(() => {
  document.removeEventListener('paste', handlePaste)
})
</script>

<style lang="scss">
.app-container {
  width: 100%;
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.header {
  height: 60px;
  background-color: white;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

  .header-left {
    display: flex;
    align-items: center;

    h1 {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
      margin: 0;
    }
  }

  .storage-info {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    color: #606266;
    background: #f5f7fa;
    padding: 4px 12px;
    border-radius: 4px;

    .storage-bar {
      width: 100px;
      height: 4px;
      background: #e4e7ed;
      border-radius: 2px;
      overflow: hidden;

      .storage-progress {
        height: 100%;
        background: #409eff;
        border-radius: 2px;
        transition: width 0.3s ease;

        &.warning {
          background: #e6a23c;
        }

        &.danger {
          background: #f56c6c;
        }
      }
    }

    .storage-text {
      min-width: 45px;
      text-align: right;
    }
  }
}

.nav-tabs {
  background: white;
  padding: 0 20px;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

  .tab-list {
    display: flex;
    gap: 40px;

    .tab-item {
      padding: 14px 0;
      font-size: 14px;
      color: #606266;
      cursor: pointer;
      position: relative;
      transition: all 0.3s ease;

      &.active {
        color: #409eff;
        font-weight: 500;

        &::after {
          content: '';
          position: absolute;
          bottom: -1px;
          left: 0;
          width: 100%;
          height: 2px;
          background: #409eff;
        }
      }

      &:hover {
        color: #409eff;
      }
    }
  }
}

.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.tag-filter {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  flex-wrap: wrap;
  padding: 0 0 12px;
  border-bottom: 1px solid #ebeef5;

  .tag-item {
    padding: 5px 12px;
    border-radius: 12px;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.3s ease;
    background: #f4f4f5;
    color: #909399;

    &.active {
      background: #409eff;
      color: white;
    }

    &.add-tag {
      color: #409eff;
      border: 1px dashed #409eff;
      background: transparent;
      padding: 4px 12px;

      &:hover {
        background: #ecf5ff;
      }
    }

    &:hover:not(.active):not(.add-tag) {
      background: #e9e9eb;
    }
  }
}

.manage-section {
  max-width: 720px;
  margin: 0 auto;
  padding: 16px;

  h2 {
    font-size: 15px;
    font-weight: 500;
    color: #303133;
    margin: 0 0 6px;
    display: flex;
    align-items: center;
    gap: 6px;

    .el-icon {
      color: #909399;
    }
  }

  .section-desc {
    color: #909399;
    font-size: 13px;
    margin: 0 0 20px;
  }
}

.manage-items,
.settings-items {
  background: white;
  border-radius: 4px;
  padding: 0;
  margin-bottom: 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.manage-item,
.settings-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;

  &:last-child {
    border-bottom: none;
  }

  .item-info {
    h3 {
      font-size: 14px;
      color: #303133;
      margin: 0 0 4px;
      font-weight: normal;
    }

    p {
      font-size: 12px;
      color: #909399;
      margin: 0;
    }
  }

  .el-button {
    padding: 8px 16px;
    font-size: 13px;
  }
}

.mt-32 {
  margin-top: 32px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 32px;

  .el-button {
    padding: 9px 20px;
    font-size: 13px;
  }
}
</style>